/*
 * @Description: 
 * @Author: lwx
 * @Date: 2022-11-07 14:14:29
 * @LastEditors: lwx
 * @LastEditTime: 2022-12-29 16:57:58
 */
import {
    login,
    userInfo
} from '@/api/login'
import {
    getToken,
    setToken,
    removeToken
} from '@/utils/auth'

const user = {
    state: {
        token: getToken(),
        account: '',
        name: '',
        roles: '',
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_ACCOUNT: (state, account) => {
            state.account = account
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        }
    },

    actions: {
        // 用户名登录并将token保存到cookie
        LoginByUsername({
            commit
        }, userInfo) {
            return new Promise((resolve, reject) => {
                login(userInfo).then(res => {
                    if (res.status && res.status !== 200) {
                        reject(res.msg)
                    }
                    commit('SET_TOKEN', res.token)
                    setToken(res.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetUserInfo({
            commit,
        }) {
            return new Promise((resolve, reject) => {
                userInfo().then(res => {
                    commit('SET_ROLES', res.role_describe)
                    commit('SET_ACCOUNT', res.account)
                    commit('SET_NAME', res.name)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 前端 退出登录
        FedLogOut({
            commit
        }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        },
    }
}

export default user